<template>
  <div class="app-container">
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="800px">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
      >
        <FormItems
          dialog-status="update"
          :form-items="formItems"
          :temp="temp"
          :configs="configs"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import odoo from '@/odooapi'

import { parseTime } from '@/utils'
import FormItems from '@/selfComponents/FormDialog/FormItems'

export default {
  name: 'FormDialog',
  components: { FormItems },
  directives: {},
  filters: {},

  props: {
    modelName: { type: String, default: '' }
  },

  data() {
    return {
      Model: undefined,
      actionName: '',
      title: 'Wizard',
      dialogFormVisible: false,

      formItems: [],

      temp: {},
      rules: {
        // type: [{ required: true, message: 'type is required', trigger: 'change' }],
        // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        // title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      configs: {}
    }
  },

  watch: {},

  async created() {
    this.Model = odoo.env(this.modelName)
  },

  methods: {
    set_form_configs(row) {
      const formItems = this.formItems.reduce((acc, item) => {
        acc[item.name] = item
        return acc
      }, {})

      this.configs = {
        handleHidden: (hidden, fi) => {
          // console.log('xxxxx,222, handleHidden', hidden)
          return hidden({ self: this.Model, temp: this.temp, items: formItems })
        },

        handleReadonly: (readonly, fi) => {
          // console.log('xxxxx,222, handleReadonly', readonly)
          return readonly({ self: this.Model })
        },

        get_options: fi => {
          // 在configs中定义了该函数, 返回 options
          // 该 options 与当前 form 中的数据有关
          // console.log('xxxxxxxx, wizard,get_options, ', this.detailData)
          return fi.options_for_select({
            self: this.Model,
            options_for_select: fi.options_for_select_init,
            row,
            temp: this.temp,
            items: formItems,
            activeRecord: this.detailData
          })
        }
      }
    },
    async handleUpdate(row, { actionName, detailData }) {
      this.detailData = detailData
      this.actionName = actionName
      const action = this.Model.configs.workflow.actions[actionName]
      // this.formItems = await this.Model.formOptions(formItems)
      const formItems = action.wizard.formItems

      // const formItems = await this.Model.env(action.wizard.model).formOptions(
      //   action.wizard.formItems
      // )

      this.formItems = formItems

      this.rules = this.formItems.reduce((acc, cur) => {
        const temp = {
          required: true,
          message: '请输入信息!',
          trigger: 'change'
        }

        if (['textarea', 'input', 'number'].includes(cur.type)) {
          temp.trigger = 'blur'
        }

        acc[cur.name] = [{ ...temp, ...(cur.rules || {}) }]
        return acc
      }, {})

      const tempData = formItems.reduce(
        (acc, cur) => {
          acc[cur.name] = cur.default
          return acc
        },
        { id: undefined }
      )

      this.temp = tempData

      this.temp = Object.keys(this.temp).reduce((acc, cur) => {
        acc[cur] = row[cur]
        return acc
      }, {})

      this.set_form_configs(row)

      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    get_values() {
      const tempData = Object.assign({}, this.temp)
      this.formItems.forEach(item => {
        if (item.type === 'date') {
          const date = tempData[item.name]
          if (date) {
            tempData[item.name] = parseTime(date, '{y}-{m}-{d}')
          }
        } else if (item.type === 'date_month') {
          const date_month = tempData[item.name]
          if (date_month) {
            const new_date = `${parseTime(date_month, '{y}-{m}')}-01`
            tempData[item.name] = new_date
          }
        } else if (item.type === 'select' && !item.multiple) {
          const val = tempData[item.name]
          if (!val) {
            tempData[item.name] = null
          }
        } else if (item.type === 'select' && item.multiple) {
          tempData[item.name] = [[6, 0, tempData[item.name]]]
        }
      })

      return tempData
    },

    submit() {
      this.$refs['dataForm'].validate(async valid => {
        if (valid) {
          const tempData = this.get_values()
          const res = await this.Model.wizard_submit(
            this.actionName,
            tempData,
            { record: this.detailData }
          )

          if (res) {
            this.$emit('changed', res)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          }

          // this.Model[method](tempData).then(res => {
          //   // this.getList()
          //   this.$emit('changed', res)
          //   this.dialogFormVisible = false
          //   this.$notify({
          //     title: '成功',
          //     message: '修改成功',
          //     type: 'success',
          //     duration: 2000
          //   })
          // })
        }
      })
    }
  }
}
</script>
